#!/bin/bash

API="https://wsuuus.info/v1/get_backup_database"

# ---------- 0) 辅助函数 ----------
die() { echo -e "\e[31m$*\e[0m" >&2; exit 1; }

# ---------- 1) 拉取数据 ----------
resp=$(curl -fsSL "$API")   || die "curl 请求失败"
[[ $(jq -r '.code' <<<"$resp") == "200" ]] || die "接口返回异常"

# ---------- 2) 统计条目 ----------
backups_path='.data.data'
total=$(jq "$backups_path | length" <<<"$resp")
(( total > 0 )) || die "未获取到任何备份条目"

# ---------- 3) 列表展示 ----------
echo -e "\n==== 备份列表 ===="
idx=1
jq -c "$backups_path[]" <<<"$resp" | while IFS= read -r item; do
    printf "[%02d]\n" "$idx"
    printf "  name: %s\n"            "$(jq -r '.name'                  <<<"$item")"
    printf "  sql_backup: %s\n"      "$(jq -r '.sql_url'        <<<"$item")"
    printf "  website_backup: %s\n\n" "$(jq -r '.website_url'    <<<"$item")"
    ((idx++))
done

# ---------- 4) 用户选择 ----------
while true; do
    read -rp "请输入编号（范围 1-${total}）: " choice_raw
    # 删除前导 0
    choice=$((10#$choice_raw))
    if (( choice>=1 && choice<=total )); then
        break
    else
        echo "编号无效，请重新输入。"
    fi
done

# ---------- 5) 提取并导出 ----------
selected=$(jq -c "$backups_path[$((choice-1))]" <<<"$resp")

export backup_name=$(jq -r '.name' <<<"$selected")
export sql_backup_url=$(jq -r '.sql_url' <<<"$selected")
export website_backup_url=$(jq -r '.website_url' <<<"$selected")

echo -e "\n====== 你选择了 ======"
echo "name           = $backup_name"
echo "sql_backup     = $sql_backup_url"
echo "website_backup = $website_backup_url"

######################
# 关键数据
CONFIG_FILE="$HOME/.wpinstall_config"
MYSQL_ROOT_PASSWORD=$(grep -m1 -E "^MYSQL_ROOT_PASSWORD:" ${CONFIG_FILE} | cut -d':' -f2 | xargs)
MYSQL_DATABASE=$(grep -m1 -E "^MYSQL_DATABASE:" ${CONFIG_FILE} | cut -d':' -f2 | xargs)
MYSQL_USER=$(grep -m1 -E "^MYSQL_USER:" ${CONFIG_FILE} | cut -d':' -f2 | xargs)
MYSQL_PASSWORD=$(grep -m1 -E "^MYSQL_PASSWORD:" ${CONFIG_FILE} | cut -d':' -f2 | xargs)
DOMAIN=$(grep -m1 -E "^domain:" ${CONFIG_FILE} | cut -d':' -f2 | xargs)

echo
echo "=== 停止wordpress ==="
cd /data/wp
docker-compose stop wordpress
echo "恢复网站数据中..."
# 保证唯一性
restore_dir=/data/wp/restore_files
if [ -d ${restore_dir} ];then
    rm -rf ${restore_dir}
fi
mkdir -p ${restore_dir}
cd ${restore_dir}
echo "下载备份数据中..."
wget $sql_backup_url
wget $website_backup_url

sql_backup_file=$(echo $sql_backup_url | awk -F'/' '{print $NF}')
website_backup_file=$(echo $website_backup_url | awk -F'/' '{print $NF}')
######### 判断压缩包格式
yasuo_info=$(file $website_backup_file)
echo $yasuo_info | grep "gzip compressed data" &> /dev/null
if [[ $? -eq 0 ]];then
    # gzip压缩
    mkdir html
    tar -xvf $website_backup_file -C html
else
    # 假设默认为zip包
    unzip $website_backup_file -d html
fi

chown --reference=../data/html -R html
rm -rf ../data/html
mv html ../data
cd ../data/html
wp_config=wp-config.php
sed -i -E "s/define[[:space:]]*\([[:space:]]*['\"]DB_NAME['\"][[:space:]]*,[[:space:]]*['\"][^'\"]*['\"][[:space:]]*\);/define( 'DB_NAME', '${MYSQL_DATABASE}' );/" ${wp_config}
sed -i -E "s/define[[:space:]]*\([[:space:]]*['\"]DB_USER['\"][[:space:]]*,[[:space:]]*['\"][^'\"]*['\"][[:space:]]*\);/define( 'DB_USER', '${MYSQL_USER}' );/" ${wp_config}
sed -i -E "s/define[[:space:]]*\([[:space:]]*['\"]DB_PASSWORD['\"][[:space:]]*,[[:space:]]*['\"][^'\"]*['\"][[:space:]]*\);/define( 'DB_PASSWORD', '${MYSQL_PASSWORD}' );/" ${wp_config}
sed -i -E "s/define[[:space:]]*\([[:space:]]*['\"]DB_HOST['\"][[:space:]]*,[[:space:]]*['\"][^'\"]*['\"][[:space:]]*\);/define( 'DB_HOST', 'db' );/" ${wp_config}
tab_prefix=$(grep "\$table_prefix[[:space:]]*=" ${wp_config} | awk -F "'" '{print $2}')

cat > .htaccess << _EOF_
 # BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
_EOF_


###########################
echo "恢复数据库中..."
cd ${restore_dir}

docker-compose exec -T db \
  bash -c "mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD} ${MYSQL_DATABASE}" < ${sql_backup_file}

cd /data/wp
OLD_DOMAIN=$(docker-compose exec db   mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD}   -e "SELECT option_value FROM ${tab_prefix}options WHERE  option_value LIKE 'https://%';"  ${MYSQL_DATABASE} | grep https:// | head -1 | sed -E 's~.*https?://([^/[:space:]]+).*~\1~')
docker-compose exec db   mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD}   -e "UPDATE ${tab_prefix}options SET option_value = replace(option_value, '${OLD_DOMAIN}', '${DOMAIN}') WHERE option_value LIKE '%${OLD_DOMAIN}%';"  ${MYSQL_DATABASE} 
docker-compose exec db   mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD}   -e "UPDATE ${tab_prefix}posts SET post_content = replace(post_content, '${OLD_DOMAIN}', '${DOMAIN}') WHERE post_content LIKE '%${OLD_DOMAIN}%';"  ${MYSQL_DATABASE} 
docker-compose exec db   mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD}   -e "UPDATE ${tab_prefix}posts SET guid = replace(guid, '${OLD_DOMAIN}', '${DOMAIN}') WHERE guid LIKE '%${OLD_DOMAIN}%';"  ${MYSQL_DATABASE} 


cd /data/wp
echo
echo "=== 启动wordpress ==="
docker-compose start wordpress

echo "恢复完成，现在可通过 https://${DOMAIN} 访问。"
